<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="第12篇：方法, 张亚飞,飞凡空间,国学,Python,Go">
    <meta name="description" content="一、方法定义在函数声明时，在其名字之前放上一个变量，即是一个方法。这个附加的参数会将该函数附加到这种类型上，即相当于为这种类型定义了一个独占的方法。
Golang方法总是绑定对象实例，并隐式将实例作为第一实参 (receiver)。

只能">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
	<meta name="baidu-site-verification" content="code-w2ezfaoXE0" />
    <title>第12篇：方法 | 飞凡空间</title>
    <link rel="icon" type="image/png" href="/medias/my-logo.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">
    
    <script src="/libs/jquery/jquery.min.js"></script>
    
<meta name="generator" content="Hexo 5.2.0">
<style>.github-emoji { position: relative; display: inline-block; width: 1.2em; min-height: 1.2em; overflow: hidden; vertical-align: top; color: transparent; }  .github-emoji > span { position: relative; z-index: 10; }  .github-emoji img, .github-emoji .fancybox { margin: 0 !important; padding: 0 !important; border: none !important; outline: none !important; text-decoration: none !important; user-select: none !important; cursor: auto !important; }  .github-emoji img { height: 1.2em !important; width: 1.2em !important; position: absolute !important; left: 50% !important; top: 50% !important; transform: translate(-50%, -50%) !important; user-select: none !important; cursor: auto !important; } .github-emoji-fallback { color: inherit; } .github-emoji-fallback img { opacity: 0 !important; }</style>
<link rel="alternate" href="/atom.xml" title="飞凡空间" type="application/atom+xml">
<link rel="stylesheet" href="/css/prism-tomorrow.css" type="text/css">
<link rel="stylesheet" href="/css/prism-line-numbers.css" type="text/css"></head>


<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/my-logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">飞凡空间</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友情链接</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>

<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/my-logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">飞凡空间</div>
        <div class="logo-desc">
            
            诚者，天之道也；诚之者，人之道也。诚者，不勉而中，不思而得。从容中道，圣人也；诚之者，择善而固执者也。
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友情链接
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        
    </ul>
</div>

        </div>

        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('https://zhangyafei-1258643511.cos.ap-nanjing.myqcloud.com/Go/blog/12.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <div class="description center-align post-title">
                        第12篇：方法
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        margin: 35px 0 15px 0;
        padding-left: 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #toc-content .is-active-link::before {
        background-color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/Go%E4%B9%8B%E8%B7%AF/">
                                <span class="chip bg-color">Go之路</span>
                            </a>
                        
                            <a href="/tags/%E7%BB%93%E6%9E%84%E4%BD%93/">
                                <span class="chip bg-color">结构体</span>
                            </a>
                        
                            <a href="/tags/%E6%96%B9%E6%B3%95/">
                                <span class="chip bg-color">方法</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/Go/" class="post-category">
                                Go
                            </a>
                        
                            <a href="/categories/Go/base/" class="post-category">
                                base
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2020-12-29
                </div>
                

                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    8.3k
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>阅读时长:&nbsp;&nbsp;
                    34 分
                </div>
                
				
                
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="far fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
            
        </div>
        <hr class="clearfix">
        <div class="card-content article-card-content">
            <div id="articleContent">
                <h3 id="一、方法定义"><a href="#一、方法定义" class="headerlink" title="一、方法定义"></a>一、方法定义</h3><p>在函数声明时，在其名字之前放上一个变量，即是一个方法。这个附加的参数会将该函数附加到这种类型上，即相当于为这种类型定义了一个独占的方法。</p>
<p><code>Golang</code>方法总是绑定对象实例，并隐式将实例作为第一实参 (receiver)。</p>
<ul>
<li>只能为当前包内命名类型定义方法。</li>
<li>参数 receiver 可任意命名。如方法中未曾使用 ，可省略参数名。</li>
<li>参数 receiver 类型可以是 T 或 *T。基类型 T 不能是接口或指针。 </li>
<li>不支持方法重载，receiver 只是参数签名的组成部分。</li>
<li>可用实例 value 或 pointer 调用全部方法，编译器自动转换。</li>
</ul>
<p>一个方法就是一个包含了接受者的函数，接受者可以是命名类型或者结构体类型的一个值或者是一个指针。所有给定类型的方法属于该类型的方法集。</p>
<h4 id="1-方法声明"><a href="#1-方法声明" class="headerlink" title="1. 方法声明"></a>1. 方法声明</h4><pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">func</span> <span class="token punctuation">(</span>recevier <span class="token keyword">type</span><span class="token punctuation">)</span> <span class="token function">methodName</span><span class="token punctuation">(</span>参数列表<span class="token punctuation">)</span><span class="token punctuation">(</span>返回值列表<span class="token punctuation">)</span><span class="token punctuation">{</span><span class="token punctuation">}</span>

参数和返回值可以省略<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">package</span> main

<span class="token keyword">type</span> Test <span class="token keyword">struct</span><span class="token punctuation">{</span><span class="token punctuation">}</span>

<span class="token comment" spellcheck="true">// 无参数、无返回值</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>t Test<span class="token punctuation">)</span> <span class="token function">method0</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>

<span class="token punctuation">}</span>

<span class="token comment" spellcheck="true">// 单参数、无返回值</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>t Test<span class="token punctuation">)</span> <span class="token function">method1</span><span class="token punctuation">(</span>i <span class="token builtin">int</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>

<span class="token punctuation">}</span>

<span class="token comment" spellcheck="true">// 多参数、无返回值</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>t Test<span class="token punctuation">)</span> <span class="token function">method2</span><span class="token punctuation">(</span>x<span class="token punctuation">,</span> y <span class="token builtin">int</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>

<span class="token punctuation">}</span>

<span class="token comment" spellcheck="true">// 无参数、单返回值</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>t Test<span class="token punctuation">)</span> <span class="token function">method3</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">(</span>i <span class="token builtin">int</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span>
<span class="token punctuation">}</span>

<span class="token comment" spellcheck="true">// 多参数、多返回值</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>t Test<span class="token punctuation">)</span> <span class="token function">method4</span><span class="token punctuation">(</span>x<span class="token punctuation">,</span> y <span class="token builtin">int</span><span class="token punctuation">)</span> <span class="token punctuation">(</span>z <span class="token builtin">int</span><span class="token punctuation">,</span> err <span class="token builtin">error</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span>
<span class="token punctuation">}</span>

<span class="token comment" spellcheck="true">// 无参数、无返回值</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>t <span class="token operator">*</span>Test<span class="token punctuation">)</span> <span class="token function">method5</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>

<span class="token punctuation">}</span>

<span class="token comment" spellcheck="true">// 单参数、无返回值</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>t <span class="token operator">*</span>Test<span class="token punctuation">)</span> <span class="token function">method6</span><span class="token punctuation">(</span>i <span class="token builtin">int</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>

<span class="token punctuation">}</span>

<span class="token comment" spellcheck="true">// 多参数、无返回值</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>t <span class="token operator">*</span>Test<span class="token punctuation">)</span> <span class="token function">method7</span><span class="token punctuation">(</span>x<span class="token punctuation">,</span> y <span class="token builtin">int</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>

<span class="token punctuation">}</span>

<span class="token comment" spellcheck="true">// 无参数、单返回值</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>t <span class="token operator">*</span>Test<span class="token punctuation">)</span> <span class="token function">method8</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">(</span>i <span class="token builtin">int</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span>
<span class="token punctuation">}</span>

<span class="token comment" spellcheck="true">// 多参数、多返回值</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>t <span class="token operator">*</span>Test<span class="token punctuation">)</span> <span class="token function">method9</span><span class="token punctuation">(</span>x<span class="token punctuation">,</span> y <span class="token builtin">int</span><span class="token punctuation">)</span> <span class="token punctuation">(</span>z <span class="token builtin">int</span><span class="token punctuation">,</span> err <span class="token builtin">error</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span>
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span><span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>下面定义一个结构体类型和该类型的一个方法：</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">package</span> main

<span class="token keyword">import</span> <span class="token punctuation">(</span>
    <span class="token string">"fmt"</span>
<span class="token punctuation">)</span>

<span class="token comment" spellcheck="true">//结构体</span>
<span class="token keyword">type</span> User <span class="token keyword">struct</span> <span class="token punctuation">{</span>
    Name  <span class="token builtin">string</span>
    Email <span class="token builtin">string</span>
<span class="token punctuation">}</span>

<span class="token comment" spellcheck="true">//方法</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>u User<span class="token punctuation">)</span> <span class="token function">Notify</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"%v : %v \n"</span><span class="token punctuation">,</span> u<span class="token punctuation">.</span>Name<span class="token punctuation">,</span> u<span class="token punctuation">.</span>Email<span class="token punctuation">)</span>
<span class="token punctuation">}</span>
<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token comment" spellcheck="true">// 值类型调用方法</span>
    u1 <span class="token operator">:=</span> User<span class="token punctuation">{</span><span class="token string">"golang"</span><span class="token punctuation">,</span> <span class="token string">"golang@golang.com"</span><span class="token punctuation">}</span>
    u1<span class="token punctuation">.</span><span class="token function">Notify</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token comment" spellcheck="true">// 指针类型调用方法</span>
    u2 <span class="token operator">:=</span> User<span class="token punctuation">{</span><span class="token string">"go"</span><span class="token punctuation">,</span> <span class="token string">"go@go.com"</span><span class="token punctuation">}</span>
    u3 <span class="token operator">:=</span> <span class="token operator">&amp;</span>u2
    u3<span class="token punctuation">.</span><span class="token function">Notify</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>输出结果：</p>
<pre><code>golang : golang@golang.com 
go : go@go.com</code></pre>
<p>解释： 首先我们定义了一个叫做 User 的结构体类型，然后定义了一个该类型的方法叫做 Notify，该方法的接受者是一个 User 类型的值。要调用 Notify 方法我们需要一个 User 类型的值或者指针。</p>
<p>在这个例子中当我们使用指针时，Go 调整和解引用指针使得调用可以被执行。注意，当接受者不是一个指针时，该方法操作对应接受者的值的副本(意思就是即使你使用了指针调用函数，但是函数的接受者是值类型，所以函数内部操作还是对副本的操作，而不是指针操作。</p>
<p>我们修改 Notify 方法，让它的接受者使用指针类型：</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">package</span> main

<span class="token keyword">import</span> <span class="token punctuation">(</span>
    <span class="token string">"fmt"</span>
<span class="token punctuation">)</span>

<span class="token comment" spellcheck="true">//结构体</span>
<span class="token keyword">type</span> User <span class="token keyword">struct</span> <span class="token punctuation">{</span>
    Name  <span class="token builtin">string</span>
    Email <span class="token builtin">string</span>
<span class="token punctuation">}</span>

<span class="token comment" spellcheck="true">//方法</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>u <span class="token operator">*</span>User<span class="token punctuation">)</span> <span class="token function">Notify</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"%v : %v \n"</span><span class="token punctuation">,</span> u<span class="token punctuation">.</span>Name<span class="token punctuation">,</span> u<span class="token punctuation">.</span>Email<span class="token punctuation">)</span>
<span class="token punctuation">}</span>
<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token comment" spellcheck="true">// 值类型调用方法</span>
    u1 <span class="token operator">:=</span> User<span class="token punctuation">{</span><span class="token string">"golang"</span><span class="token punctuation">,</span> <span class="token string">"golang@golang.com"</span><span class="token punctuation">}</span>
    u1<span class="token punctuation">.</span><span class="token function">Notify</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token comment" spellcheck="true">// 指针类型调用方法</span>
    u2 <span class="token operator">:=</span> User<span class="token punctuation">{</span><span class="token string">"go"</span><span class="token punctuation">,</span> <span class="token string">"go@go.com"</span><span class="token punctuation">}</span>
    u3 <span class="token operator">:=</span> <span class="token operator">&amp;</span>u2
    u3<span class="token punctuation">.</span><span class="token function">Notify</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>输出结果：</p>
<pre><code>golang : golang@golang.com 
go : go@go.com</code></pre>
<p>注意：当接受者是指针时，即使用值类型调用那么函数内部也是对指针的操作。</p>
<p>方法不过是一种特殊的函数，只需将其还原，就知道 receiver T 和 <code>*T</code> 的差别。</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">package</span> main

<span class="token keyword">import</span> <span class="token string">"fmt"</span>

<span class="token keyword">type</span> Data <span class="token keyword">struct</span> <span class="token punctuation">{</span>
    x <span class="token builtin">int</span>
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token punctuation">(</span>self Data<span class="token punctuation">)</span> <span class="token function">ValueTest</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span> <span class="token comment" spellcheck="true">// func ValueTest(self Data);</span>
    fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"Value: %p\n"</span><span class="token punctuation">,</span> <span class="token operator">&amp;</span>self<span class="token punctuation">)</span>
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token punctuation">(</span>self <span class="token operator">*</span>Data<span class="token punctuation">)</span> <span class="token function">PointerTest</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span> <span class="token comment" spellcheck="true">// func PointerTest(self *Data);</span>
    fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"Pointer: %p\n"</span><span class="token punctuation">,</span> self<span class="token punctuation">)</span>
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    d <span class="token operator">:=</span> Data<span class="token punctuation">{</span><span class="token punctuation">}</span>
    p <span class="token operator">:=</span> <span class="token operator">&amp;</span>d
    fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"Data: %p\n"</span><span class="token punctuation">,</span> p<span class="token punctuation">)</span>

    d<span class="token punctuation">.</span><span class="token function">ValueTest</span><span class="token punctuation">(</span><span class="token punctuation">)</span>   <span class="token comment" spellcheck="true">// ValueTest(d)</span>
    d<span class="token punctuation">.</span><span class="token function">PointerTest</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token comment" spellcheck="true">// PointerTest(&amp;d)</span>

    p<span class="token punctuation">.</span><span class="token function">ValueTest</span><span class="token punctuation">(</span><span class="token punctuation">)</span>   <span class="token comment" spellcheck="true">// ValueTest(*p)</span>
    p<span class="token punctuation">.</span><span class="token function">PointerTest</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token comment" spellcheck="true">// PointerTest(p)</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>输出:</p>
<pre><code>Data: 0xc42007c008
Value: 0xc42007c018
Pointer: 0xc42007c008
Value: 0xc42007c020
Pointer: 0xc42007c008</code></pre>
<h4 id="2-普通函数与方法的区别"><a href="#2-普通函数与方法的区别" class="headerlink" title="2. 普通函数与方法的区别"></a>2. 普通函数与方法的区别</h4><ul>
<li>对于普通函数，接收者为值类型时，不能将指针类型的数据直接传递，反之亦然。</li>
<li>对于方法（如struct的方法），接收者为值类型时，可以直接用指针类型的变量调用方法，反过来同样也可以。</li>
</ul>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">package</span> main

<span class="token comment" spellcheck="true">//普通函数与方法的区别（在接收者分别为值类型和指针类型的时候）</span>

<span class="token keyword">import</span> <span class="token punctuation">(</span>
    <span class="token string">"fmt"</span>
<span class="token punctuation">)</span>

<span class="token comment" spellcheck="true">//1.普通函数</span>
<span class="token comment" spellcheck="true">//接收值类型参数的函数</span>
<span class="token keyword">func</span> <span class="token function">valueIntTest</span><span class="token punctuation">(</span>a <span class="token builtin">int</span><span class="token punctuation">)</span> <span class="token builtin">int</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> a <span class="token operator">+</span> <span class="token number">10</span>
<span class="token punctuation">}</span>

<span class="token comment" spellcheck="true">//接收指针类型参数的函数</span>
<span class="token keyword">func</span> <span class="token function">pointerIntTest</span><span class="token punctuation">(</span>a <span class="token operator">*</span><span class="token builtin">int</span><span class="token punctuation">)</span> <span class="token builtin">int</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> <span class="token operator">*</span>a <span class="token operator">+</span> <span class="token number">10</span>
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token function">structTestValue</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    a <span class="token operator">:=</span> <span class="token number">2</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"valueIntTest:"</span><span class="token punctuation">,</span> <span class="token function">valueIntTest</span><span class="token punctuation">(</span>a<span class="token punctuation">)</span><span class="token punctuation">)</span>
    <span class="token comment" spellcheck="true">//函数的参数为值类型，则不能直接将指针作为参数传递</span>
    <span class="token comment" spellcheck="true">//fmt.Println("valueIntTest:", valueIntTest(&amp;a))</span>
    <span class="token comment" spellcheck="true">//compile error: cannot use &amp;a (type *int) as type int in function argument</span>

    b <span class="token operator">:=</span> <span class="token number">5</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"pointerIntTest:"</span><span class="token punctuation">,</span> <span class="token function">pointerIntTest</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>b<span class="token punctuation">)</span><span class="token punctuation">)</span>
    <span class="token comment" spellcheck="true">//同样，当函数的参数为指针类型时，也不能直接将值类型作为参数传递</span>
    <span class="token comment" spellcheck="true">//fmt.Println("pointerIntTest:", pointerIntTest(b))</span>
    <span class="token comment" spellcheck="true">//compile error:cannot use b (type int) as type *int in function argument</span>
<span class="token punctuation">}</span>

<span class="token comment" spellcheck="true">//2.方法</span>
<span class="token keyword">type</span> PersonD <span class="token keyword">struct</span> <span class="token punctuation">{</span>
    id   <span class="token builtin">int</span>
    name <span class="token builtin">string</span>
<span class="token punctuation">}</span>

<span class="token comment" spellcheck="true">//接收者为值类型</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>p PersonD<span class="token punctuation">)</span> <span class="token function">valueShowName</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>p<span class="token punctuation">.</span>name<span class="token punctuation">)</span>
<span class="token punctuation">}</span>

<span class="token comment" spellcheck="true">//接收者为指针类型</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>p <span class="token operator">*</span>PersonD<span class="token punctuation">)</span> <span class="token function">pointShowName</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>p<span class="token punctuation">.</span>name<span class="token punctuation">)</span>
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token function">structTestFunc</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token comment" spellcheck="true">//值类型调用方法</span>
    personValue <span class="token operator">:=</span> PersonD<span class="token punctuation">{</span><span class="token number">101</span><span class="token punctuation">,</span> <span class="token string">"hello world"</span><span class="token punctuation">}</span>
    personValue<span class="token punctuation">.</span><span class="token function">valueShowName</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    personValue<span class="token punctuation">.</span><span class="token function">pointShowName</span><span class="token punctuation">(</span><span class="token punctuation">)</span>

    <span class="token comment" spellcheck="true">//指针类型调用方法</span>
    personPointer <span class="token operator">:=</span> <span class="token operator">&amp;</span>PersonD<span class="token punctuation">{</span><span class="token number">102</span><span class="token punctuation">,</span> <span class="token string">"hello golang"</span><span class="token punctuation">}</span>
    personPointer<span class="token punctuation">.</span><span class="token function">valueShowName</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    personPointer<span class="token punctuation">.</span><span class="token function">pointShowName</span><span class="token punctuation">(</span><span class="token punctuation">)</span>

    <span class="token comment" spellcheck="true">//与普通函数不同，接收者为指针类型和值类型的方法，指针类型和值类型的变量均可相互调用</span>
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token function">structTestValue</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token function">structTestFunc</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>输出结果：</p>
<pre><code>valueIntTest: 12
pointerIntTest: 15
hello world
hello world
hello golang
hello golang</code></pre>
<h4 id="3-基于指针对象的方法"><a href="#3-基于指针对象的方法" class="headerlink" title="3. 基于指针对象的方法"></a>3. 基于指针对象的方法</h4><p>当调用一个函数时，会对其每一个参数值进行拷贝，如果一个函数需要更新一个变量，或者函数的其中一个参数实在太大我们希望能够避免进行这种默认的拷贝，这种情况下我们就需要用到指针了。对应到我们这里用来更新接收器的对象的方法，当这个接受者变量本身比较大时，我们就可以用其指针而不是对象来声明方法，如下：</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">func</span> <span class="token punctuation">(</span>p <span class="token operator">*</span>Point<span class="token punctuation">)</span> <span class="token function">ScaleBy</span><span class="token punctuation">(</span>factor <span class="token builtin">float64</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    p<span class="token punctuation">.</span>X <span class="token operator">*=</span> factor
    p<span class="token punctuation">.</span>Y <span class="token operator">*=</span> factor
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
<p>这个方法的名字是<code>(*Point).ScaleBy</code>。这里的括号是必须的；没有括号的话这个表达式可能会被理解为<code>*(Point.ScaleBy)</code>。</p>
<p>在现实的程序里，一般会约定如果Point这个类有一个指针作为接收器的方法，那么所有Point的方法都必须有一个指针接收器，即使是那些并不需要这个指针接收器的函数。我们在这里打破了这个约定只是为了展示一下两种方法的异同而已。</p>
<p>只有类型(Point)和指向他们的指针<code>(*Point)</code>，才可能是出现在接收器声明里的两种接收器。此外，为了避免歧义，在声明方法时，如果一个类型名本身是一个指针的话，是不允许其出现在接收器中的，比如下面这个例子：</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">type</span> P <span class="token operator">*</span><span class="token builtin">int</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>P<span class="token punctuation">)</span> <span class="token function">f</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span> <span class="token comment" spellcheck="true">/* ... */</span> <span class="token punctuation">}</span> <span class="token comment" spellcheck="true">// compile error: invalid receiver type</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<p>想要调用指针类型方法<code>(*Point).ScaleBy</code>，只要提供一个Point类型的指针即可，像下面这样。</p>
<pre class="line-numbers language-go"><code class="language-go">r <span class="token operator">:=</span> <span class="token operator">&amp;</span>Point<span class="token punctuation">{</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">}</span>
r<span class="token punctuation">.</span><span class="token function">ScaleBy</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span>
fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token operator">*</span>r<span class="token punctuation">)</span> <span class="token comment" spellcheck="true">// "{2, 4}"</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<p>或者这样：</p>
<pre class="line-numbers language-go"><code class="language-go">p <span class="token operator">:=</span> Point<span class="token punctuation">{</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">}</span>
pptr <span class="token operator">:=</span> <span class="token operator">&amp;</span>p
pptr<span class="token punctuation">.</span><span class="token function">ScaleBy</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span>
fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>p<span class="token punctuation">)</span> <span class="token comment" spellcheck="true">// "{2, 4}"</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
<p>或者这样:</p>
<pre class="line-numbers language-go"><code class="language-go">p <span class="token operator">:=</span> Point<span class="token punctuation">{</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">}</span>
<span class="token punctuation">(</span><span class="token operator">&amp;</span>p<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">ScaleBy</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span>
fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>p<span class="token punctuation">)</span> <span class="token comment" spellcheck="true">// "{2, 4}"</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<p>不过后面两种方法有些笨拙。幸运的是，go语言本身在这种地方会帮到我们。如果接收器p是一个Point类型的变量，并且其方法需要一个Point指针作为接收器，我们可以用下面这种简短的写法：</p>
<pre class="line-numbers language-go"><code class="language-go">p<span class="token punctuation">.</span><span class="token function">ScaleBy</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>编译器会隐式地帮我们用&amp;p去调用<code>ScaleBy</code>这个方法。这种简写方法只适用于“变量”，包括struct里的字段比如<code>p.X</code>，以及array和slice内的元素比如<code>perim[0]</code>。我们不能通过一个无法取到地址的接收器来调用指针方法，比如临时变量的内存地址就无法获取得到：</p>
<pre class="line-numbers language-go"><code class="language-go">Point<span class="token punctuation">{</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">}</span><span class="token punctuation">.</span><span class="token function">ScaleBy</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span> <span class="token comment" spellcheck="true">// compile error: can't take address of Point literal</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>但是我们可以用一个<code>*Point</code>这样的接收器来调用Point的方法，因为我们可以通过地址来找到这个变量，只要用解引用符号<code>*</code>来取到该变量即可。编译器在这里也会给我们隐式地插入<code>*</code>这个操作符，所以下面这两种写法等价的：</p>
<pre class="line-numbers language-Go"><code class="language-Go">pptr.Distance(q)
(*pptr).Distance(q)<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<p>这里的几个例子可能让你有些困惑，所以我们总结一下：在每一个合法的方法调用表达式中，也就是下面三种情况里的任意一种情况都是可以的：</p>
<p>不论接收器的实际参数和其形式参数是相同，比如两者都是类型T或者都是类型<code>*T</code>：</p>
<pre class="line-numbers language-go"><code class="language-go">Point<span class="token punctuation">{</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">}</span><span class="token punctuation">.</span><span class="token function">Distance</span><span class="token punctuation">(</span>q<span class="token punctuation">)</span> <span class="token comment" spellcheck="true">//  Point</span>
pptr<span class="token punctuation">.</span><span class="token function">ScaleBy</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span>         <span class="token comment" spellcheck="true">// *Point</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<p>或者接收器实参是类型T，但接收器形参是类型<code>*T</code>，这种情况下编译器会隐式地为我们取变量的地址：</p>
<pre class="line-numbers language-go"><code class="language-go">p<span class="token punctuation">.</span><span class="token function">ScaleBy</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span> <span class="token comment" spellcheck="true">// implicit (&amp;p)</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>或者接收器实参是类型<code>*T</code>，形参是类型T。编译器会隐式地为我们解引用，取到指针指向的实际变量：</p>
<pre class="line-numbers language-go"><code class="language-go">pptr<span class="token punctuation">.</span><span class="token function">Distance</span><span class="token punctuation">(</span>q<span class="token punctuation">)</span> <span class="token comment" spellcheck="true">// implicit (*pptr)</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>如果命名类型T（译注：用type xxx定义的类型）的所有方法都是用T类型自己来做接收器（而不是<code>*T</code>），那么拷贝这种类型的实例就是安全的；调用他的任何一个方法也就会产生一个值的拷贝。比如time.Duration的这个类型，在调用其方法时就会被全部拷贝一份，包括在作为参数传入函数的时候。但是如果一个方法使用指针作为接收器，你需要避免对其进行拷贝，因为这样可能会破坏掉该类型内部的不变性。比如你对bytes.Buffer对象进行了拷贝，那么可能会引起原始对象和拷贝对象只是别名而已，实际上它们指向的对象是一样的。紧接着对拷贝后的变量进行修改可能会有让你有意外的结果。</p>
<p><strong>译注：</strong> 这里说的比较绕，其实有两点：</p>
<ol>
<li>不管你的method的receiver是指针类型还是非指针类型，都是可以通过指针/非指针类型进行调用的，编译器会帮你做类型转换。</li>
<li>在声明一个method的receiver该是指针还是非指针类型时，你需要考虑两方面的因素，第一方面是这个对象本身是不是特别大，如果声明为非指针变量时，调用会产生一次拷贝；第二方面是如果你用指针类型作为receiver，那么你一定要注意，这种指针类型指向的始终是一块内存地址，就算你对其进行了拷贝。</li>
</ol>
<h4 id="4-Nil也是一个合法的接收器类型"><a href="#4-Nil也是一个合法的接收器类型" class="headerlink" title="4. Nil也是一个合法的接收器类型"></a>4. Nil也是一个合法的接收器类型</h4><p>就像一些函数允许nil指针作为参数一样，方法理论上也可以用nil指针作为其接收器，尤其当nil对于对象来说是合法的零值时，比如map或者slice。在下面的简单<code>int</code>链表的例子里，nil代表的是空链表：</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token comment" spellcheck="true">// An IntList is a linked list of integers.</span>
<span class="token comment" spellcheck="true">// A nil *IntList represents the empty list.</span>
<span class="token keyword">type</span> IntList <span class="token keyword">struct</span> <span class="token punctuation">{</span>
    Value <span class="token builtin">int</span>
    Tail  <span class="token operator">*</span>IntList
<span class="token punctuation">}</span>
<span class="token comment" spellcheck="true">// Sum returns the sum of the list elements.</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>list <span class="token operator">*</span>IntList<span class="token punctuation">)</span> <span class="token function">Sum</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">int</span> <span class="token punctuation">{</span>
    <span class="token keyword">if</span> list <span class="token operator">==</span> <span class="token boolean">nil</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> <span class="token number">0</span>
    <span class="token punctuation">}</span>
    <span class="token keyword">return</span> list<span class="token punctuation">.</span>Value <span class="token operator">+</span> list<span class="token punctuation">.</span>Tail<span class="token punctuation">.</span><span class="token function">Sum</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>当你定义一个允许nil作为接收器值的方法的类型时，在类型前面的注释中指出nil变量代表的意义是很有必要的，就像我们上面例子里做的这样。</p>
<p>下面是<code>net/url</code>包里Values类型定义的一部分。</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">package</span> url

<span class="token comment" spellcheck="true">// Values maps a string key to a list of values.</span>
<span class="token keyword">type</span> Values <span class="token keyword">map</span><span class="token punctuation">[</span><span class="token builtin">string</span><span class="token punctuation">]</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">string</span>
<span class="token comment" spellcheck="true">// Get returns the first value associated with the given key,</span>
<span class="token comment" spellcheck="true">// or "" if there are none.</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>v Values<span class="token punctuation">)</span> <span class="token function">Get</span><span class="token punctuation">(</span>key <span class="token builtin">string</span><span class="token punctuation">)</span> <span class="token builtin">string</span> <span class="token punctuation">{</span>
    <span class="token keyword">if</span> vs <span class="token operator">:=</span> v<span class="token punctuation">[</span>key<span class="token punctuation">]</span><span class="token punctuation">;</span> <span class="token function">len</span><span class="token punctuation">(</span>vs<span class="token punctuation">)</span> <span class="token operator">></span> <span class="token number">0</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> vs<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span>
    <span class="token punctuation">}</span>
    <span class="token keyword">return</span> <span class="token string">""</span>
<span class="token punctuation">}</span>
<span class="token comment" spellcheck="true">// Add adds the value to key.</span>
<span class="token comment" spellcheck="true">// It appends to any existing values associated with key.</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>v Values<span class="token punctuation">)</span> <span class="token function">Add</span><span class="token punctuation">(</span>key<span class="token punctuation">,</span> value <span class="token builtin">string</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    v<span class="token punctuation">[</span>key<span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token function">append</span><span class="token punctuation">(</span>v<span class="token punctuation">[</span>key<span class="token punctuation">]</span><span class="token punctuation">,</span> value<span class="token punctuation">)</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>这个定义向外部暴露了一个map的命名类型，并且提供了一些能够简单操作这个map的方法。这个map的value字段是一个string的slice，所以这个Values是一个多维map。客户端使用这个变量的时候可以使用map固有的一些操作(make，切片，m[key]等等)，也可以使用这里提供的操作方法，或者两者并用，都是可以的：</p>
<pre class="line-numbers language-go"><code class="language-go">m <span class="token operator">:=</span> url<span class="token punctuation">.</span>Values<span class="token punctuation">{</span><span class="token string">"lang"</span><span class="token punctuation">:</span> <span class="token punctuation">{</span><span class="token string">"en"</span><span class="token punctuation">}</span><span class="token punctuation">}</span> <span class="token comment" spellcheck="true">// direct construction</span>
m<span class="token punctuation">.</span><span class="token function">Add</span><span class="token punctuation">(</span><span class="token string">"item"</span><span class="token punctuation">,</span> <span class="token string">"1"</span><span class="token punctuation">)</span>
m<span class="token punctuation">.</span><span class="token function">Add</span><span class="token punctuation">(</span><span class="token string">"item"</span><span class="token punctuation">,</span> <span class="token string">"2"</span><span class="token punctuation">)</span>

fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>m<span class="token punctuation">.</span><span class="token function">Get</span><span class="token punctuation">(</span><span class="token string">"lang"</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token comment" spellcheck="true">// "en"</span>
fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>m<span class="token punctuation">.</span><span class="token function">Get</span><span class="token punctuation">(</span><span class="token string">"q"</span><span class="token punctuation">)</span><span class="token punctuation">)</span>    <span class="token comment" spellcheck="true">// ""</span>
fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>m<span class="token punctuation">.</span><span class="token function">Get</span><span class="token punctuation">(</span><span class="token string">"item"</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token comment" spellcheck="true">// "1"      (first value)</span>
fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>m<span class="token punctuation">[</span><span class="token string">"item"</span><span class="token punctuation">]</span><span class="token punctuation">)</span>     <span class="token comment" spellcheck="true">// "[1 2]"  (direct map access)</span>

m <span class="token operator">=</span> <span class="token boolean">nil</span>
fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>m<span class="token punctuation">.</span><span class="token function">Get</span><span class="token punctuation">(</span><span class="token string">"item"</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token comment" spellcheck="true">// ""</span>
m<span class="token punctuation">.</span><span class="token function">Add</span><span class="token punctuation">(</span><span class="token string">"item"</span><span class="token punctuation">,</span> <span class="token string">"3"</span><span class="token punctuation">)</span>         <span class="token comment" spellcheck="true">// panic: assignment to entry in nil map</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>对Get的最后一次调用中，nil接收器的行为即是一个空map的行为。我们可以等价地将这个操作写成Value(nil).Get(“item”)，但是如果你直接写<code>nil.Get("item")</code>的话是无法通过编译的，因为nil的字面量编译器无法判断其准确类型。所以相比之下，最后的那行<code>m.Add</code>的调用就会产生一个panic，因为他尝试更新一个空map。</p>
<p>由于<code>url.Values</code>是一个map类型，并且间接引用了其key/value对，因此<code>url.Values.Add</code>对这个map里的元素做任何的更新、删除操作对调用方都是可见的。实际上，就像在普通函数中一样，虽然可以通过引用来操作内部值，但在方法想要修改引用本身时是不会影响原始值的，比如把他置换为nil，或者让这个引用指向了其它的对象，调用方都不会受影响。（译注：因为传入的是存储了内存地址的变量，你改变这个变量本身是影响不了原始的变量的，想想C语言，是差不多的）</p>
<h3 id="二、匿名字段"><a href="#二、匿名字段" class="headerlink" title="二、匿名字段"></a>二、匿名字段</h3><p><strong>Go支持只提供类型而不写字段名的方式，也就是匿名字段，也称为嵌入字段</strong></p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">package</span> main

<span class="token keyword">import</span> <span class="token string">"fmt"</span>

<span class="token comment" spellcheck="true">//    go支持只提供类型而不写字段名的方式，也就是匿名字段，也称为嵌入字段</span>

<span class="token comment" spellcheck="true">//人</span>
<span class="token keyword">type</span> Person <span class="token keyword">struct</span> <span class="token punctuation">{</span>
    name <span class="token builtin">string</span>
    sex  <span class="token builtin">string</span>
    age  <span class="token builtin">int</span>
<span class="token punctuation">}</span>

<span class="token keyword">type</span> Student <span class="token keyword">struct</span> <span class="token punctuation">{</span>
    Person
    id   <span class="token builtin">int</span>
    addr <span class="token builtin">string</span>
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token comment" spellcheck="true">// 初始化</span>
    s1 <span class="token operator">:=</span> Student<span class="token punctuation">{</span>Person<span class="token punctuation">{</span><span class="token string">"5lmh"</span><span class="token punctuation">,</span> <span class="token string">"man"</span><span class="token punctuation">,</span> <span class="token number">20</span><span class="token punctuation">}</span><span class="token punctuation">,</span> <span class="token number">1</span><span class="token punctuation">,</span> <span class="token string">"bj"</span><span class="token punctuation">}</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>s1<span class="token punctuation">)</span>

    s2 <span class="token operator">:=</span> Student<span class="token punctuation">{</span>Person<span class="token punctuation">:</span> Person<span class="token punctuation">{</span><span class="token string">"5lmh"</span><span class="token punctuation">,</span> <span class="token string">"man"</span><span class="token punctuation">,</span> <span class="token number">20</span><span class="token punctuation">}</span><span class="token punctuation">}</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>s2<span class="token punctuation">)</span>

    s3 <span class="token operator">:=</span> Student<span class="token punctuation">{</span>Person<span class="token punctuation">:</span> Person<span class="token punctuation">{</span>name<span class="token punctuation">:</span> <span class="token string">"5lmh"</span><span class="token punctuation">}</span><span class="token punctuation">}</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>s3<span class="token punctuation">)</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>输出结果：</p>
<pre><code>{{5lmh man 20} 1 bj}
{{5lmh man 20} 0 }
{{5lmh  0} 0 }
```

#### 1. 同名字段的情况

```go
package main

import "fmt"

//人
type Person struct {
    name string
    sex  string
    age  int
}

type Student struct {
    Person
    id   int
    addr string
    //同名字段
    name string
}

func main() {
    var s Student
    // 给自己字段赋值了
    s.name = "5lmh"
    fmt.Println(s)

    // 若给父类同名字段赋值，如下
    s.Person.name = "枯藤"
    fmt.Println(s)
}
```

输出结果：

```
{{  0} 0  5lmh}
{{枯藤  0} 0  5lmh}
```

#### 2. 所有的内置类型和自定义类型都是可以作为匿名字段去使用

```go
package main

import "fmt"

//人
type Person struct {
    name string
    sex  string
    age  int
}

// 自定义类型
type mystr string

// 学生
type Student struct {
    Person
    int
    mystr
}

func main() {
    s1 := Student{Person{"5lmh", "man", 18}, 1, "bj"}
    fmt.Println(s1)
}
```

输出结果：

```
{{5lmh man 18} 1 bj}
```

#### 3. 指针类型匿名字段

```go
package main

import "fmt"

//人
type Person struct {
    name string
    sex  string
    age  int
}

// 学生
type Student struct {
    *Person
    id   int
    addr string
}

func main() {
    s1 := Student{&amp;Person{"5lmh", "man", 18}, 1, "bj"}
    fmt.Println(s1)
    fmt.Println(s1.name)
    fmt.Println(s1.Person.name)
}
```

输出结果：

```
{0xc00005c360 1 bj}
zs
zs
```

#### 4. 继承和方法重载

```go
package main

import "fmt"

type User struct {
    id   int
    name string
}

type Manager struct {
    User
}

func (self *User) ToString() string { // receiver = &amp;(Manager.User)
    return fmt.Sprintf("User: %p, %v", self, self)
}

func main() {
    m := Manager{User{1, "Tom"}}
    fmt.Printf("Manager: %p\n", &amp;m)
    fmt.Println(m.ToString())
}</code></pre>
<p>输出结果:</p>
<pre><code>Manager: 0xc42000a060
User: 0xc42000a060, &amp;{1 Tom}</code></pre>
<p>通过匿名字段，可获得和继承类似的复用能力。依据编译器查找次序，只需在外层定义同名方法，就可以实现 “override”。</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">package</span> main

<span class="token keyword">import</span> <span class="token string">"fmt"</span>

<span class="token keyword">type</span> User <span class="token keyword">struct</span> <span class="token punctuation">{</span>
    id   <span class="token builtin">int</span>
    name <span class="token builtin">string</span>
<span class="token punctuation">}</span>

<span class="token keyword">type</span> Manager <span class="token keyword">struct</span> <span class="token punctuation">{</span>
    User
    title <span class="token builtin">string</span>
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token punctuation">(</span>self <span class="token operator">*</span>User<span class="token punctuation">)</span> <span class="token function">ToString</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">string</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> fmt<span class="token punctuation">.</span><span class="token function">Sprintf</span><span class="token punctuation">(</span><span class="token string">"User: %p, %v"</span><span class="token punctuation">,</span> self<span class="token punctuation">,</span> self<span class="token punctuation">)</span>
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token punctuation">(</span>self <span class="token operator">*</span>Manager<span class="token punctuation">)</span> <span class="token function">ToString</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">string</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> fmt<span class="token punctuation">.</span><span class="token function">Sprintf</span><span class="token punctuation">(</span><span class="token string">"Manager: %p, %v"</span><span class="token punctuation">,</span> self<span class="token punctuation">,</span> self<span class="token punctuation">)</span>
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    m <span class="token operator">:=</span> Manager<span class="token punctuation">{</span>User<span class="token punctuation">{</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token string">"Tom"</span><span class="token punctuation">}</span><span class="token punctuation">,</span> <span class="token string">"Administrator"</span><span class="token punctuation">}</span>

    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>m<span class="token punctuation">.</span><span class="token function">ToString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>

    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>m<span class="token punctuation">.</span>User<span class="token punctuation">.</span><span class="token function">ToString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>输出结果:</p>
<pre><code>Manager: 0xc420074180, &amp;{{1 Tom} Administrator}
User: 0xc420074180, &amp;{1 Tom}
```

### 三、方法集

#### 1. 方法集的定义

`Golang`方法集 ：每个类型都有与之关联的方法集，把这个类型的所有方法称为类型的方法集，这会影响到接口实现规则。

```go
type Student struct {
   age int8
   name string
} 
 
func (s Student) showName() {
   fmt.Println(s.name)
}
 
func (s * Student) setName(newName string) {
   s.name = newName
}
```

类型Student方法集包含了`showName()`方法，类型*Student方法集包含了`showName()`方法和`setName()`方法。

为什么呢？因为：

- 类型 T 方法集，包含全部 receiver T 方法。
- 类型 *T 方法集，包含全部 receiver T + *T 方法。

#### 2. 方法集和方法接受者的关系

在上面的案例中，类型Student的方法集并不包含了`setName()`方法，那么是不是Student类型变量，就不能调用`setName()`方法呢？即下面调用，是否会报错呢？

```makefile
s := Student{}
s.setName("dq")
```

其实，上面的调用是ok的。为什么呢？我们来回顾一下go语言的方法定义。

- 参数 receiver 可任意命名，如方法中，不使用参数，可以省略参数名。
- 参数 receiver 类型可以是 T 或 *T，但类型T不能为接口或指针类型。
- 不支持方法重载。
- 实例value或pointer可以调用全部的方法，编译器会自动转换。

如下：

```go
type Student struct {
   age int8
   name string
}

type StudentPoint *Student

func (Student) sayHello() {  //省略receiver 的参数参数名字
   fmt.Println("hello world")
}

func (s Student) showName() { 
   fmt.Println(s.name)
}

func (s * Student) setName(newName string) {
   s.name = newName
}

func (s StudentPoint) showName2(){ // Error：接受者(receiver)为指针类型
   fmt.Println(s.name)
}
s := Student{}
s.setName("dq")  // go会自动转为 (&amp;s).setName("dq")

var s2 = &amp;s
s2.showName()    // o会自动转为 (*s2).showName()
```

所以，当类型调用自己申明的方法的时候，不需要考虑方法集。方法接受者是值类型（T），还是指针类型(*T)，影响T类型的实体变量的方法集。

#### 3. 方法集和接口

**接口的定义**

接口是一个或多个方法签名的集合。任何类型的方法集中只要拥有该接口“对应的全部方法”声名。就表示它 "实现" 了该接口，无须在该类型上显式声明实现了哪个接口。接口具有如下特点：

- 对应的全部方法：是指有相同名称、参数列表 (不包括参数名) 以及返回值。
- 接口只有方法的声明，没有实现。
- 接口可以匿名嵌入到其他接口，或是嵌入结构体中。
- 接口命名习惯以` er` 结尾。

```typescript
type Personer interface { //定义一个接口
   showName()
}
 
type Student struct {
   Personer //嵌入接口
}
```

**接口执行机制**

- 接口对象，是由接口表（interface table）和数据指针组成。
- 接口表示存储元数据信息，包括接口类型、动态类型，以及实现接口的方法指针。
- 数据指针持有的是目标对象的只读复制品，复制完整对象或指针。

```go

package main
 
import (
   "fmt"
   "reflect"
)
 
type User struct {
   id   int
   name string
}
 
type Student struct {
   id   int
   name string
}
 
func main() {
   u := User{1, "Tom"}
   var i interface{} = u // 由于interface{}不包含任何方法，所以任何类型，都实现了interface{}接口
   fmt.Println(reflect.TypeOf(i)) //main.User
 
   i = Student{}
   fmt.Println(reflect.TypeOf(i)) //main.Student
}
```

**以实体类型和以指针类型实现接口的区别**

1. 若以实体类型（T）实现接口，不管是T类型的值，还是T类型的指针，都实现了该接口。
2. 若以指针类型（*T）实现接口，只有T类型的指针，才实现了该接口。

```go
type Animal interface { //接口
   say()
}
 
type Dog struct {
   name string
}
 
type Cat struct {
   name string
}
 
func (_self Dog) say() {
   fmt.Println("I am", _self.name)
}
 
func (_self *Cat) say() {
   fmt.Println("I am", _self.name)
}
 
func main() {
   var d1 Animal= Dog{name:"wangCai1"}
   d1.say() //因为Dog 的value类型实现了Animal接口
 
   var d2 Animal= &amp;Dog{name:"wangCai2"}
   d2.say() //因为dDog 的指针类型实现了Animal接口
 
   var c1 Animal= Cat{name:"miaoMiao1"}
   c1.say() //因为Cat 的value类型没有实现了Animal接口，所以报错
 
   var c2 Animal= &amp;Cat{name:"miaoMiao2"}
   c2.say() //因为Cat 的指针类型实现了Animal接口
}
```

类型必须实现接口的所有方法，才能表示它 "实现" 了该接口，如下：

```go

type Animal interface {
   say()
   doSome()
}
 
type Dog struct {
   name string
}
func (_self Dog) say() {
   fmt.Println("I am", _self.name)
}
func (_self *Dog) doSome() {
   fmt.Println("I will do something")
}
 
func main() {
   // 报错，因为Dog的value类型实现了Animal接口的say方法没有实现doSome方法
   var d1 Animal= Dog{name:"wangCai1"} 
   d1.say()
 
   //因为dDog 的指针类型实现了Animal接口集的所有方法
   var d2 Animal= &amp;Dog{name:"wangCai2"}
   d2.say() 
}
```

#### 4. 方法集和嵌入

**什么是嵌入**

go语言中，所谓的嵌入，即把一个类型作为另外一个类型的匿名字段。如下：

```go
type Person struct {
   age  int8
   name string
}
 
type Student struct {
   Person //嵌人 Person类型
}
```

go语言通过嵌入组合，来实现继承的行为。于是，我们就可以通过Student类型的实例，访问`Persion`类型的变量和方法。如下：

```javascript
var s = Student{}
s.name = "dq"
```

**值类型(T)嵌入和指针类型(*T)嵌入的区别**

```cpp

type Student1 struct {
   Person //值类型的嵌入
}
type Student2 struct {
   *Person //指针类型的嵌入
}
```

要理解这个区别，就有知道go语言中类型的默认值。如下：

- 数值类型（如int8、int16、uint等），默认值为0；
- 布尔类型，默认值为false；
- 字符串类型，默认值为""
- 指针、通道、切片、字典等，默认值为nil
- 复合类型的默认值，为所包含类型的默认值。

所以：

```go
type Person struct {
   age  int8
   name string
}
 
func (s Person) showName() {
   fmt.Println(s.name)
}
 
func (s *Person) setName(newName string) {
   s.name = newName
}
 
type Student1 struct {
   Person //Student1包含了Person,那么Student1对应的value和pointer包含Person
}
 
type Student2 struct {
   *Person
}
 
// 内嵌类型 Person默认值为 Person{age:0, name:""}
s1 := Student1{}
s1.setName("student1_01") // ok
s1.showName()
 
// 内嵌类型 *Person默认值为 nil
s2 := &amp;Student2{}
s2.setName("student1_02") //Error，由于目前内嵌类型的值为nil，会触发报错
s2.showName()
 
// 给嵌入类型一个复制，就ok了
s3 := &amp;Student2{Person:&amp;Person{age:3, name:"s3"}}
//s3 := &amp;Student2{&amp;Person{age:3, name:"s3"}} 和上一行等价
s3.showName()</code></pre>
<p>在上面的案例中变量s2中嵌入类型默认值为nil，故会报错：panic: runtime error: invalid memory address or nil pointer dereference</p>
<p>所以，针对指针嵌入类型，在使用前，需要赋值。</p>
<p><strong>嵌入和方法集的关系</strong></p>
<ul>
<li>类型 S 包含匿名字段 T，则 S和*S 方法集包含 T 方法。</li>
<li>类型 S 包含匿名字段*T，则 S和 *S 方法集包含 T + *T 方法。</li>
<li>不管嵌入的是T还是 *<strong>T</strong> ，*S方法集，包含 T + *T 方法。</li>
</ul>
<p>下面，通过案例来解析，如下，思考Student1的指针和实例类型，以及Student2的指针和实例类型，是否实现了Human接口呢？</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">type</span> Human <span class="token keyword">interface</span> <span class="token punctuation">{</span> <span class="token comment" spellcheck="true">//定义接口</span>
   <span class="token function">showName</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
   <span class="token function">setName</span><span class="token punctuation">(</span><span class="token builtin">string</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>

<span class="token keyword">type</span> Person <span class="token keyword">struct</span> <span class="token punctuation">{</span> 
   age  <span class="token builtin">int8</span>
   name <span class="token builtin">string</span>
<span class="token punctuation">}</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>s Person<span class="token punctuation">)</span> <span class="token function">showName</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span> <span class="token comment" spellcheck="true">// Person类型的实例和指针，都实现了Human的showName方法</span>
   fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>s<span class="token punctuation">.</span>name<span class="token punctuation">)</span>
<span class="token punctuation">}</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>s <span class="token operator">*</span>Person<span class="token punctuation">)</span> <span class="token function">setName</span><span class="token punctuation">(</span>newName <span class="token builtin">string</span><span class="token punctuation">)</span> <span class="token punctuation">{</span> <span class="token comment" spellcheck="true">// 只有Person类型的指针，才实现了Human的setNanme方法</span>
   s<span class="token punctuation">.</span>name <span class="token operator">=</span> newName
<span class="token punctuation">}</span>

<span class="token keyword">type</span> Student1 <span class="token keyword">struct</span> <span class="token punctuation">{</span> <span class="token comment" spellcheck="true">// 以值类型，嵌入</span>
   Person
<span class="token punctuation">}</span>

<span class="token keyword">type</span> Student2 <span class="token keyword">struct</span> <span class="token punctuation">{</span>  <span class="token comment" spellcheck="true">// 以指针类型，嵌入</span>
   <span class="token operator">*</span>Person
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>解析：</p>
<ol>
<li>应用上面规则1，由于Student1通过实体类型(T)方式，嵌入Person，所以 Stuednt1的实例类型，仅仅包含了接受者为Person的方法，即不包含<code>setName</code>()方法，所以Student1的实例类型，没有实现Human接口，不能赋值给Human接口；应用上面规则3， Stuednt1的指针类型，包含了接受者为Person和接受者为*Person的方法，即Stuednt1的指针类型，实现了Human接口。</li>
<li>应用上面规则2，由于Student2通过指针类型(*T)方式，嵌入Person，所以Student2的指针类型和实例类型，都实现了Human接口。</li>
</ol>
<p>所以：</p>
<pre class="line-numbers language-javascript"><code class="language-javascript"><span class="token comment" spellcheck="true">// Error 应用上面的关系判断第1条规则，因为Student1实例类型的方法集中，仅仅包含Person的实例方法集，即仅仅包含showName()方法，所以Student1的实例类型，没有实现Human接口</span>
<span class="token keyword">var</span> s1 Human <span class="token operator">=</span> Student1<span class="token punctuation">{</span><span class="token punctuation">}</span> <span class="token comment" spellcheck="true">//报错:Student1 does not implement Human (setName method has pointer receiver)</span>
s1<span class="token punctuation">.</span><span class="token function">setName</span><span class="token punctuation">(</span><span class="token string">"student1_01"</span><span class="token punctuation">)</span>
s1<span class="token punctuation">.</span><span class="token function">showName</span><span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token keyword">var</span> s2 Human <span class="token operator">=</span> <span class="token operator">&amp;</span>Student1<span class="token punctuation">{</span><span class="token punctuation">}</span> <span class="token comment" spellcheck="true">//ok 应用第1条和弟3条规则</span>
s2<span class="token punctuation">.</span><span class="token function">setName</span><span class="token punctuation">(</span><span class="token string">"student1_02"</span><span class="token punctuation">)</span>
s2<span class="token punctuation">.</span><span class="token function">showName</span><span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token keyword">var</span> s3 Human <span class="token operator">=</span> Student2<span class="token punctuation">{</span><span class="token operator">&amp;</span>Person<span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">}</span> <span class="token comment" spellcheck="true">//ok ，应用第2条规则</span>
s3<span class="token punctuation">.</span><span class="token function">setName</span><span class="token punctuation">(</span><span class="token string">"student2_01"</span><span class="token punctuation">)</span>
s3<span class="token punctuation">.</span><span class="token function">showName</span><span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token keyword">var</span> s4 Human <span class="token operator">=</span> <span class="token operator">&amp;</span>Student2<span class="token punctuation">{</span><span class="token operator">&amp;</span>Person<span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">}</span> <span class="token comment" spellcheck="true">//ok ，应用第2条规则</span>
s4<span class="token punctuation">.</span><span class="token function">setName</span><span class="token punctuation">(</span><span class="token string">"student2_02"</span><span class="token punctuation">)</span>
s4<span class="token punctuation">.</span><span class="token function">showName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h4 id="5-总结"><a href="#5-总结" class="headerlink" title="5. 总结"></a>5. 总结</h4><ul>
<li>类型 T 方法集包含全部 receiver T 方法。</li>
<li>类型 *T 方法集包含全部 receiver T + *T 方法。</li>
<li>如类型 S 包含匿名字段 T，则 S 和 *S 方法集包含 T 方法。 </li>
<li>如类型 S 包含匿名字段 *T，则 S 和 *S 方法集包含 T + *T 方法。 </li>
<li>不管嵌入 <code>T</code> 或 <code>*T</code>，*S 方法集总是包含 T + *T 方法。</li>
</ul>
<h3 id="四、表达式"><a href="#四、表达式" class="headerlink" title="四、表达式"></a>四、表达式</h3><p><code>Golang</code>表达式 ：根据调用者不同，方法分为两种表现形式:</p>
<pre class="line-numbers language-go"><code class="language-go">instance<span class="token punctuation">.</span><span class="token function">method</span><span class="token punctuation">(</span>args<span class="token operator">...</span><span class="token punctuation">)</span> <span class="token operator">--</span><span class="token operator">-</span><span class="token operator">></span> <span class="token operator">&lt;</span><span class="token keyword">type</span><span class="token operator">></span><span class="token punctuation">.</span><span class="token keyword">func</span><span class="token punctuation">(</span>instance<span class="token punctuation">,</span> args<span class="token operator">...</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>前者称为 method value，后者 method expression。</p>
<p>两者都可像普通函数那样赋值和传参，区别在于 method value 绑定实例，而 method expression 则须显式传参。</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">package</span> main

<span class="token keyword">import</span> <span class="token string">"fmt"</span>

<span class="token keyword">type</span> User <span class="token keyword">struct</span> <span class="token punctuation">{</span>
    id   <span class="token builtin">int</span>
    name <span class="token builtin">string</span>
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token punctuation">(</span>self <span class="token operator">*</span>User<span class="token punctuation">)</span> <span class="token function">Test</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"%p, %v\n"</span><span class="token punctuation">,</span> self<span class="token punctuation">,</span> self<span class="token punctuation">)</span>
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    u <span class="token operator">:=</span> User<span class="token punctuation">{</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token string">"Tom"</span><span class="token punctuation">}</span>
    u<span class="token punctuation">.</span><span class="token function">Test</span><span class="token punctuation">(</span><span class="token punctuation">)</span>

    mValue <span class="token operator">:=</span> u<span class="token punctuation">.</span>Test
    <span class="token function">mValue</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token comment" spellcheck="true">// 隐式传递 receiver</span>

    mExpression <span class="token operator">:=</span> <span class="token punctuation">(</span><span class="token operator">*</span>User<span class="token punctuation">)</span><span class="token punctuation">.</span>Test
    <span class="token function">mExpression</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>u<span class="token punctuation">)</span> <span class="token comment" spellcheck="true">// 显式传递 receiver</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>输出结果:</p>
<pre><code>0xc42000a060, &amp;{1 Tom}
0xc42000a060, &amp;{1 Tom}
0xc42000a060, &amp;{1 Tom}</code></pre>
<p>需要注意，method value 会复制 receiver。</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">package</span> main

<span class="token keyword">import</span> <span class="token string">"fmt"</span>

<span class="token keyword">type</span> User <span class="token keyword">struct</span> <span class="token punctuation">{</span>
    id   <span class="token builtin">int</span>
    name <span class="token builtin">string</span>
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token punctuation">(</span>self User<span class="token punctuation">)</span> <span class="token function">Test</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>self<span class="token punctuation">)</span>
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    u <span class="token operator">:=</span> User<span class="token punctuation">{</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token string">"Tom"</span><span class="token punctuation">}</span>
    mValue <span class="token operator">:=</span> u<span class="token punctuation">.</span>Test <span class="token comment" spellcheck="true">// 立即复制 receiver，因为不是指针类型，不受后续修改影响。</span>

    u<span class="token punctuation">.</span>id<span class="token punctuation">,</span> u<span class="token punctuation">.</span>name <span class="token operator">=</span> <span class="token number">2</span><span class="token punctuation">,</span> <span class="token string">"Jack"</span>
    u<span class="token punctuation">.</span><span class="token function">Test</span><span class="token punctuation">(</span><span class="token punctuation">)</span>

    <span class="token function">mValue</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>输出结果</p>
<pre><code>{2 Jack}
{1 Tom}</code></pre>
<p>在汇编层面，method value 和闭包的实现方式相同，实际返回<code>FuncVal</code>类型对象。</p>
<pre class="line-numbers language-go"><code class="language-go">FuncVal <span class="token punctuation">{</span> method_address<span class="token punctuation">,</span> receiver_copy <span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>可依据方法集转换 method expression，注意 receiver 类型的差异。</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">package</span> main

<span class="token keyword">import</span> <span class="token string">"fmt"</span>

<span class="token keyword">type</span> User <span class="token keyword">struct</span> <span class="token punctuation">{</span>
    id   <span class="token builtin">int</span>
    name <span class="token builtin">string</span>
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token punctuation">(</span>self <span class="token operator">*</span>User<span class="token punctuation">)</span> <span class="token function">TestPointer</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"TestPointer: %p, %v\n"</span><span class="token punctuation">,</span> self<span class="token punctuation">,</span> self<span class="token punctuation">)</span>
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token punctuation">(</span>self User<span class="token punctuation">)</span> <span class="token function">TestValue</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"TestValue: %p, %v\n"</span><span class="token punctuation">,</span> <span class="token operator">&amp;</span>self<span class="token punctuation">,</span> self<span class="token punctuation">)</span>
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    u <span class="token operator">:=</span> User<span class="token punctuation">{</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token string">"Tom"</span><span class="token punctuation">}</span>
    fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"User: %p, %v\n"</span><span class="token punctuation">,</span> <span class="token operator">&amp;</span>u<span class="token punctuation">,</span> u<span class="token punctuation">)</span>

    mv <span class="token operator">:=</span> User<span class="token punctuation">.</span>TestValue
    <span class="token function">mv</span><span class="token punctuation">(</span>u<span class="token punctuation">)</span>

    mp <span class="token operator">:=</span> <span class="token punctuation">(</span><span class="token operator">*</span>User<span class="token punctuation">)</span><span class="token punctuation">.</span>TestPointer
    <span class="token function">mp</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>u<span class="token punctuation">)</span>

    mp2 <span class="token operator">:=</span> <span class="token punctuation">(</span><span class="token operator">*</span>User<span class="token punctuation">)</span><span class="token punctuation">.</span>TestValue <span class="token comment" spellcheck="true">// *User 方法集包含 TestValue。签名变为 func TestValue(self *User)。实际依然是 receiver value copy。</span>
    <span class="token function">mp2</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>u<span class="token punctuation">)</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>输出:</p>
<pre><code>User: 0xc42000a060, {1 Tom}
TestValue: 0xc42000a0a0, {1 Tom}
TestPointer: 0xc42000a060, &amp;{1 Tom}
TestValue: 0xc42000a100, {1 Tom}</code></pre>
<p>将方法 “还原” 成函数，就容易理解下面的代码了。</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">package</span> main

<span class="token keyword">type</span> Data <span class="token keyword">struct</span><span class="token punctuation">{</span><span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token punctuation">(</span>Data<span class="token punctuation">)</span> <span class="token function">TestValue</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span><span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token punctuation">(</span><span class="token operator">*</span>Data<span class="token punctuation">)</span> <span class="token function">TestPointer</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span><span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">var</span> p <span class="token operator">*</span>Data <span class="token operator">=</span> <span class="token boolean">nil</span>
    p<span class="token punctuation">.</span><span class="token function">TestPointer</span><span class="token punctuation">(</span><span class="token punctuation">)</span>

    <span class="token punctuation">(</span><span class="token operator">*</span>Data<span class="token punctuation">)</span><span class="token punctuation">(</span><span class="token boolean">nil</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">TestPointer</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token comment" spellcheck="true">// method value</span>
    <span class="token punctuation">(</span><span class="token operator">*</span>Data<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">TestPointer</span><span class="token punctuation">(</span><span class="token boolean">nil</span><span class="token punctuation">)</span>   <span class="token comment" spellcheck="true">// method expression</span>

    <span class="token comment" spellcheck="true">// p.TestValue()            // invalid memory address or nil pointer dereference</span>

    <span class="token comment" spellcheck="true">// (Data)(nil).TestValue()  // cannot convert nil to type Data</span>
    <span class="token comment" spellcheck="true">// Data.TestValue(nil)      // cannot use nil as type Data in function argument</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h3 id="五、自定义error"><a href="#五、自定义error" class="headerlink" title="五、自定义error"></a>五、自定义error</h3><h4 id="1-系统抛"><a href="#1-系统抛" class="headerlink" title="1. 系统抛"></a>1. 系统抛</h4><pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">package</span> main

<span class="token keyword">import</span> <span class="token string">"fmt"</span>

<span class="token comment" spellcheck="true">// 系统抛</span>
<span class="token keyword">func</span> <span class="token function">test01</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
   a <span class="token operator">:=</span> <span class="token punctuation">[</span><span class="token number">5</span><span class="token punctuation">]</span><span class="token builtin">int</span><span class="token punctuation">{</span><span class="token number">0</span><span class="token punctuation">,</span> <span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">,</span> <span class="token number">4</span><span class="token punctuation">}</span>
   a<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token number">123</span>
   fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>a<span class="token punctuation">)</span>
   <span class="token comment" spellcheck="true">//a[10] = 11</span>
   index <span class="token operator">:=</span> <span class="token number">10</span>
   a<span class="token punctuation">[</span>index<span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token number">10</span>
   fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>a<span class="token punctuation">)</span>
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token function">getCircleArea</span><span class="token punctuation">(</span>radius <span class="token builtin">float32</span><span class="token punctuation">)</span> <span class="token punctuation">(</span>area <span class="token builtin">float32</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
   <span class="token keyword">if</span> radius <span class="token operator">&lt;</span> <span class="token number">0</span> <span class="token punctuation">{</span>
      <span class="token comment" spellcheck="true">// 自己抛</span>
      <span class="token function">panic</span><span class="token punctuation">(</span><span class="token string">"半径不能为负"</span><span class="token punctuation">)</span>
   <span class="token punctuation">}</span>
   <span class="token keyword">return</span> <span class="token number">3.14</span> <span class="token operator">*</span> radius <span class="token operator">*</span> radius
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token function">test02</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
   <span class="token function">getCircleArea</span><span class="token punctuation">(</span><span class="token operator">-</span><span class="token number">5</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token function">test03</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
   <span class="token comment" spellcheck="true">// 延时执行匿名函数</span>
   <span class="token comment" spellcheck="true">// 延时到何时？（1）程序正常结束   （2）发生异常时</span>
   <span class="token keyword">defer</span> <span class="token keyword">func</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
      <span class="token comment" spellcheck="true">// recover() 复活 恢复</span>
      <span class="token comment" spellcheck="true">// 会返回程序为什么挂了</span>
      <span class="token keyword">if</span> err <span class="token operator">:=</span> <span class="token function">recover</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">{</span>
         fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span>
      <span class="token punctuation">}</span>
   <span class="token punctuation">}</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
   <span class="token function">getCircleArea</span><span class="token punctuation">(</span><span class="token operator">-</span><span class="token number">5</span><span class="token punctuation">)</span>
   fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"这里有没有执行"</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token function">test04</span><span class="token punctuation">(</span><span class="token punctuation">)</span>  <span class="token punctuation">{</span>
   <span class="token function">test03</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
   fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"test04"</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
   <span class="token function">test04</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>

<span class="token comment" spellcheck="true">/*
半径不能为负
test04
 */</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h4 id="2-返回异常"><a href="#2-返回异常" class="headerlink" title="2. 返回异常"></a>2. 返回异常</h4><pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">package</span> main

<span class="token keyword">import</span> <span class="token punctuation">(</span>
   <span class="token string">"errors"</span>
   <span class="token string">"fmt"</span>
<span class="token punctuation">)</span>

<span class="token keyword">func</span> <span class="token function">getCircleArea</span><span class="token punctuation">(</span>radius <span class="token builtin">float32</span><span class="token punctuation">)</span> <span class="token punctuation">(</span>area <span class="token builtin">float32</span><span class="token punctuation">,</span> err <span class="token builtin">error</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
   <span class="token keyword">if</span> radius <span class="token operator">&lt;</span> <span class="token number">0</span> <span class="token punctuation">{</span>
      <span class="token comment" spellcheck="true">// 构建个异常对象</span>
      err <span class="token operator">=</span> errors<span class="token punctuation">.</span><span class="token function">New</span><span class="token punctuation">(</span><span class="token string">"半径不能为负"</span><span class="token punctuation">)</span>
      <span class="token keyword">return</span>
   <span class="token punctuation">}</span>
   area <span class="token operator">=</span> <span class="token number">3.14</span> <span class="token operator">*</span> radius <span class="token operator">*</span> radius
   <span class="token keyword">return</span>
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
   area<span class="token punctuation">,</span> err <span class="token operator">:=</span> <span class="token function">getCircleArea</span><span class="token punctuation">(</span><span class="token operator">-</span><span class="token number">5</span><span class="token punctuation">)</span>
   <span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">{</span>
      fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span>
   <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
      fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>area<span class="token punctuation">)</span>
   <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h4 id="3-自定义error："><a href="#3-自定义error：" class="headerlink" title="3. 自定义error："></a>3. 自定义error：</h4><pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">package</span> main

<span class="token keyword">import</span> <span class="token punctuation">(</span>
    <span class="token string">"fmt"</span>
    <span class="token string">"os"</span>
    <span class="token string">"time"</span>
<span class="token punctuation">)</span>

<span class="token keyword">type</span> PathError <span class="token keyword">struct</span> <span class="token punctuation">{</span>
    path       <span class="token builtin">string</span>
    op         <span class="token builtin">string</span>
    createTime <span class="token builtin">string</span>
    message    <span class="token builtin">string</span>
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token punctuation">(</span>p <span class="token operator">*</span>PathError<span class="token punctuation">)</span> <span class="token function">Error</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">string</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> fmt<span class="token punctuation">.</span><span class="token function">Sprintf</span><span class="token punctuation">(</span><span class="token string">"path=%s \nop=%s \ncreateTime=%s \nmessage=%s"</span><span class="token punctuation">,</span> p<span class="token punctuation">.</span>path<span class="token punctuation">,</span>
        p<span class="token punctuation">.</span>op<span class="token punctuation">,</span> p<span class="token punctuation">.</span>createTime<span class="token punctuation">,</span> p<span class="token punctuation">.</span>message<span class="token punctuation">)</span>
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token function">Open</span><span class="token punctuation">(</span>filename <span class="token builtin">string</span><span class="token punctuation">)</span> <span class="token builtin">error</span> <span class="token punctuation">{</span>

    file<span class="token punctuation">,</span> err <span class="token operator">:=</span> os<span class="token punctuation">.</span><span class="token function">Open</span><span class="token punctuation">(</span>filename<span class="token punctuation">)</span>
    <span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> <span class="token operator">&amp;</span>PathError<span class="token punctuation">{</span>
            path<span class="token punctuation">:</span>       filename<span class="token punctuation">,</span>
            op<span class="token punctuation">:</span>         <span class="token string">"read"</span><span class="token punctuation">,</span>
            message<span class="token punctuation">:</span>    err<span class="token punctuation">.</span><span class="token function">Error</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
            createTime<span class="token punctuation">:</span> fmt<span class="token punctuation">.</span><span class="token function">Sprintf</span><span class="token punctuation">(</span><span class="token string">"%v"</span><span class="token punctuation">,</span> time<span class="token punctuation">.</span><span class="token function">Now</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">defer</span> file<span class="token punctuation">.</span><span class="token function">Close</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token keyword">return</span> <span class="token boolean">nil</span>
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    err <span class="token operator">:=</span> <span class="token function">Open</span><span class="token punctuation">(</span><span class="token string">"/Users/5lmh/Desktop/go/src/test.txt"</span><span class="token punctuation">)</span>
    <span class="token keyword">switch</span> v <span class="token operator">:=</span> err<span class="token punctuation">.</span><span class="token punctuation">(</span><span class="token keyword">type</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">case</span> <span class="token operator">*</span>PathError<span class="token punctuation">:</span>
        fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"get path error,"</span><span class="token punctuation">,</span> v<span class="token punctuation">)</span>
    <span class="token keyword">default</span><span class="token punctuation">:</span>

    <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>输出结果：</p>
<pre><code>get path error, path=/Users/pprof/Desktop/go/src/test.txt 
op=read 
createTime=2018-04-05 11:25:17.331915 +0800 CST m=+0.000441790 
message=open /Users/pprof/Desktop/go/src/test.txt: no such file or directory</code></pre>
<h3 id="六、封装"><a href="#六、封装" class="headerlink" title="六、封装"></a>六、封装</h3><h4 id="1-可见性"><a href="#1-可见性" class="headerlink" title="1. 可见性"></a>1. 可见性</h4><p>一个对象的变量或者方法如果对调用方是不可见的话，一般就被定义为“封装”。封装有时候也被叫做信息隐藏，同时也是面向对象编程最关键的一个方面。</p>
<p>Go语言只有一种控制可见性的手段：大写首字母的标识符会从定义它们的包中被导出，小写字母的则不会。这种限制包内成员的方式同样适用于struct或者一个类型的方法。因而如果我们想要封装一个对象，我们必须将其定义为一个struct。</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">type</span> IntSet <span class="token keyword">struct</span> <span class="token punctuation">{</span>
    words <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">uint64</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<p>当然，我们也可以把IntSet定义为一个slice类型，但这样我们就需要把代码中所有方法里用到的<code>s.words</code>用<code>*s</code>替换掉了：</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">type</span> IntSet <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">uint64</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>尽管这个版本的<code>IntSet</code>在本质上是一样的，但它也允许其它包中可以直接读取并编辑这个slice。换句话说，相对于<code>*s</code>这个表达式会出现在所有的包中，<code>s.words</code>只需要在定义<code>IntSet</code>的包中出现。</p>
<p>这种基于名字的手段使得在语言中最小的封装单元是package，而不是像其它语言一样的类型。一个struct类型的字段对同一个包的所有代码都有可见性，无论你的代码是写在一个函数还是一个方法里。</p>
<h4 id="2-封装的优点"><a href="#2-封装的优点" class="headerlink" title="2. 封装的优点"></a>2. 封装的优点</h4><p>封装提供了三方面的优点。</p>
<ul>
<li><p>首先，因为调用方不能直接修改对象的变量值，其只需要关注少量的语句并且只要弄懂少量变量的可能的值即可。</p>
</li>
<li><p>第二，隐藏实现的细节，可以防止调用方依赖那些可能变化的具体实现，这样使设计包的程序员在不破坏对外的api情况下能得到更大的自由。</p>
<p>把bytes.Buffer这个类型作为例子来考虑。这个类型在做短字符串叠加的时候很常用，所以在设计的时候可以做一些预先的优化，比如提前预留一部分空间，来避免反复的内存分配。又因为Buffer是一个struct类型，这些额外的空间可以用附加的字节数组来保存，且放在一个小写字母开头的字段中。这样在外部的调用方只能看到性能的提升，但并不会得到这个附加变量。Buffer和其增长算法我们列在这里，为了简洁性稍微做了一些精简：</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">type</span> Buffer <span class="token keyword">struct</span> <span class="token punctuation">{</span>
    buf     <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">byte</span>
    initial <span class="token punctuation">[</span><span class="token number">64</span><span class="token punctuation">]</span><span class="token builtin">byte</span>
    <span class="token comment" spellcheck="true">/* ... */</span>
<span class="token punctuation">}</span>

<span class="token comment" spellcheck="true">// Grow expands the buffer's capacity, if necessary,</span>
<span class="token comment" spellcheck="true">// to guarantee space for another n bytes. [...]</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>b <span class="token operator">*</span>Buffer<span class="token punctuation">)</span> <span class="token function">Grow</span><span class="token punctuation">(</span>n <span class="token builtin">int</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">if</span> b<span class="token punctuation">.</span>buf <span class="token operator">==</span> <span class="token boolean">nil</span> <span class="token punctuation">{</span>
        b<span class="token punctuation">.</span>buf <span class="token operator">=</span> b<span class="token punctuation">.</span>initial<span class="token punctuation">[</span><span class="token punctuation">:</span><span class="token number">0</span><span class="token punctuation">]</span> <span class="token comment" spellcheck="true">// use preallocated space initially</span>
    <span class="token punctuation">}</span>
    <span class="token keyword">if</span> <span class="token function">len</span><span class="token punctuation">(</span>b<span class="token punctuation">.</span>buf<span class="token punctuation">)</span><span class="token operator">+</span>n <span class="token operator">></span> <span class="token function">cap</span><span class="token punctuation">(</span>b<span class="token punctuation">.</span>buf<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        buf <span class="token operator">:=</span> <span class="token function">make</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">byte</span><span class="token punctuation">,</span> b<span class="token punctuation">.</span><span class="token function">Len</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token operator">*</span><span class="token function">cap</span><span class="token punctuation">(</span>b<span class="token punctuation">.</span>buf<span class="token punctuation">)</span> <span class="token operator">+</span> n<span class="token punctuation">)</span>
        <span class="token function">copy</span><span class="token punctuation">(</span>buf<span class="token punctuation">,</span> b<span class="token punctuation">.</span>buf<span class="token punctuation">)</span>
        b<span class="token punctuation">.</span>buf <span class="token operator">=</span> buf
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
</li>
<li><p>封装的第三个优点也是最重要的优点，是阻止了外部调用方对对象内部的值任意地进行修改。</p>
<p>因为对象内部变量只可以被同一个包内的函数修改，所以包的作者可以让这些函数确保对象内部的一些值的不变性。比如下面的Counter类型允许调用方来增加counter变量的值，并且允许将这个值reset为0，但是不允许随便设置这个值(译注：因为压根就访问不到)：</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">type</span> Counter <span class="token keyword">struct</span> <span class="token punctuation">{</span> n <span class="token builtin">int</span> <span class="token punctuation">}</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>c <span class="token operator">*</span>Counter<span class="token punctuation">)</span> <span class="token function">N</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">int</span>     <span class="token punctuation">{</span> <span class="token keyword">return</span> c<span class="token punctuation">.</span>n <span class="token punctuation">}</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>c <span class="token operator">*</span>Counter<span class="token punctuation">)</span> <span class="token function">Increment</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span> c<span class="token punctuation">.</span>n<span class="token operator">++</span> <span class="token punctuation">}</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>c <span class="token operator">*</span>Counter<span class="token punctuation">)</span> <span class="token function">Reset</span><span class="token punctuation">(</span><span class="token punctuation">)</span>     <span class="token punctuation">{</span> c<span class="token punctuation">.</span>n <span class="token operator">=</span> <span class="token number">0</span> <span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
</li>
</ul>
<h4 id="3-其他"><a href="#3-其他" class="headerlink" title="3. 其他"></a>3. 其他</h4><p><strong>只用来访问或修改内部变量的函数被称为setter或者getter</strong>。例子如下，比如log包里的Logger类型对应的一些函数。在命名一个getter方法时，我们通常会省略掉前面的Get前缀。这种简洁上的偏好也可以推广到各种类型的前缀比如Fetch，Find或者Lookup。</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">package</span> log
<span class="token keyword">type</span> Logger <span class="token keyword">struct</span> <span class="token punctuation">{</span>
    flags  <span class="token builtin">int</span>
    prefix <span class="token builtin">string</span>
    <span class="token comment" spellcheck="true">// ...</span>
<span class="token punctuation">}</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>l <span class="token operator">*</span>Logger<span class="token punctuation">)</span> <span class="token function">Flags</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">int</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>l <span class="token operator">*</span>Logger<span class="token punctuation">)</span> <span class="token function">SetFlags</span><span class="token punctuation">(</span>flag <span class="token builtin">int</span><span class="token punctuation">)</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>l <span class="token operator">*</span>Logger<span class="token punctuation">)</span> <span class="token function">Prefix</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">string</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>l <span class="token operator">*</span>Logger<span class="token punctuation">)</span> <span class="token function">SetPrefix</span><span class="token punctuation">(</span>prefix <span class="token builtin">string</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>Go的编码风格不禁止直接导出字段。当然，一旦进行了导出，就没有办法在保证API兼容的情况下去除对其的导出，所以在一开始的选择一定要经过深思熟虑并且要考虑到包内部的一些不变量的保证，未来可能的变化，以及调用方的代码质量是否会因为包的一点修改而变差。</p>
<p>虽然封装在有些情况是必要的，但有时候我们也需要暴露一些内部内容，比如：<code>time.Duration</code>将其表现暴露为一个int64数字的纳秒，使得我们可以用一般的数值操作来对时间进行对比，甚至可以定义这种类型的常量：</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">const</span> day <span class="token operator">=</span> <span class="token number">24</span> <span class="token operator">*</span> time<span class="token punctuation">.</span>Hour
fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>day<span class="token punctuation">.</span><span class="token function">Seconds</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token comment" spellcheck="true">// "86400"</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://zhangyafeii.gitee.io" rel="external nofollow noreferrer">张亚飞</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://zhangyafeii.gitee.io/go/base/di-12-pian-fang-fa/">https://zhangyafeii.gitee.io/go/base/di-12-pian-fang-fa/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="https://zhangyafeii.gitee.io" target="_blank">张亚飞</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/Go%E4%B9%8B%E8%B7%AF/">
                                    <span class="chip bg-color">Go之路</span>
                                </a>
                            
                                <a href="/tags/%E7%BB%93%E6%9E%84%E4%BD%93/">
                                    <span class="chip bg-color">结构体</span>
                                </a>
                            
                                <a href="/tags/%E6%96%B9%E6%B3%95/">
                                    <span class="chip bg-color">方法</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">

<div id="article-share">
    
    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/medias/reward/alipay.jpg" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/medias/reward/wechat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>
            
        </div>
    </div>

    
        <link rel="stylesheet" href="/libs/gitalk/gitalk.css">
<link rel="stylesheet" href="/css/my-gitalk.css">

<div class="card gitalk-card" data-aos="fade-up">
    <div class="comment_headling" style="font-size: 20px; font-weight: 700; position: relative; left: 20px; top: 15px; padding-bottom: 5px;">
        <i class="fas fa-comments fa-fw" aria-hidden="true"></i>
        <span>评论</span>
    </div>
    <div id="gitalk-container" class="card-content"></div>
</div>

<script src="/libs/gitalk/gitalk.min.js"></script>
<script>
    let gitalk = new Gitalk({
        clientID: 'b9bf0e29501275f4f23c',
        clientSecret: '1c56bc88fdb7b23ee3712916a38e5e8d1311823a',
        repo: 'github.io',
        owner: 'zhangyafeii',
        admin: "zhangyafeii",
        id: '2020-12-29T12-00-01',
        distractionFreeMode: false  // Facebook-like distraction free mode
    });

    gitalk.render('gitalk-container');
</script>
    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/go/base/di-13-pian-jie-kou/">
                    <div class="card-image">
                        
                        <img src="https://zhangyafei-1258643511.cos.ap-nanjing.myqcloud.com/Go/blog/13.jpg" class="responsive-img" alt="第13篇：接口">
                        
                        <span class="card-title">第13篇：接口</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            Go语言中的基础数据类型可以表示一些事物的基本属性，但是当我们想表达一个事物的全部或部分属性时，这时候再用单一的基本数据类型明显就无法满足需求了，Go语言提供了一种自定义数据类型，可以封装多个基本数据类型，这种数据类型叫结构体，英文名称struct。也就是我们可以通过struct来定义自己的类型了。结构体是一个复合类型，用于表示一组数据。结构体由一系列属性组成，每个属性都有自己的类型和值。Go语言中通过struct来实现面向对象。
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2020-12-30
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/Go/" class="post-category">
                                    Go
                                </a>
                            
                            <a href="/categories/Go/base/" class="post-category">
                                    base
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Go%E4%B9%8B%E8%B7%AF/">
                        <span class="chip bg-color">Go之路</span>
                    </a>
                    
                    <a href="/tags/%E6%8E%A5%E5%8F%A3/">
                        <span class="chip bg-color">接口</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/go/base/di-11-pian-jie-gou-ti/">
                    <div class="card-image">
                        
                        <img src="https://zhangyafei-1258643511.cos.ap-nanjing.myqcloud.com/Go/blog/11.jpg" class="responsive-img" alt="第11篇：Golang结构体">
                        
                        <span class="card-title">第11篇：Golang结构体</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            Go语言中的基础数据类型可以表示一些事物的基本属性，但是当我们想表达一个事物的全部或部分属性时，这时候再用单一的基本数据类型明显就无法满足需求了，Go语言提供了一种自定义数据类型，可以封装多个基本数据类型，这种数据类型叫结构体，英文名称struct。也就是我们可以通过struct来定义自己的类型了。结构体是一个复合类型，用于表示一组数据。结构体由一系列属性组成，每个属性都有自己的类型和值。Go语言中通过struct来实现面向对象。
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2020-12-28
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/Go/" class="post-category">
                                    Go
                                </a>
                            
                            <a href="/categories/Go/base/" class="post-category">
                                    base
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Go%E4%B9%8B%E8%B7%AF/">
                        <span class="chip bg-color">Go之路</span>
                    </a>
                    
                    <a href="/tags/%E5%A4%8D%E5%90%88%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B/">
                        <span class="chip bg-color">复合数据类型</span>
                    </a>
                    
                    <a href="/tags/%E5%80%BC%E7%B1%BB%E5%9E%8B/">
                        <span class="chip bg-color">值类型</span>
                    </a>
                    
                    <a href="/tags/%E7%BB%93%E6%9E%84%E4%BD%93/">
                        <span class="chip bg-color">结构体</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>


<script>
    $('#articleContent').on('copy', function (e) {
        // IE8 or earlier browser is 'undefined'
        if (typeof window.getSelection === 'undefined') return;

        var selection = window.getSelection();
        // if the selection is short let's not annoy our users.
        if (('' + selection).length < Number.parseInt('120')) {
            return;
        }

        // create a div outside of the visible area and fill it with the selected text.
        var bodyElement = document.getElementsByTagName('body')[0];
        var newdiv = document.createElement('div');
        newdiv.style.position = 'absolute';
        newdiv.style.left = '-99999px';
        bodyElement.appendChild(newdiv);
        newdiv.appendChild(selection.getRangeAt(0).cloneContents());

        // we need a <pre> tag workaround.
        // otherwise the text inside "pre" loses all the line breaks!
        if (selection.getRangeAt(0).commonAncestorContainer.nodeName === 'PRE') {
            newdiv.innerHTML = "<pre>" + newdiv.innerHTML + "</pre>";
        }

        var url = document.location.href;
        newdiv.innerHTML += '<br />'
            + '来源: 飞凡空间<br />'
            + '文章作者: 张亚飞<br />'
            + '文章链接: <a href="' + url + '">' + url + '</a><br />'
            + '本文章著作权归作者所有，任何形式的转载都请注明出处。';

        selection.selectAllChildren(newdiv);
        window.setTimeout(function () {bodyElement.removeChild(newdiv);}, 200);
    });
</script>


<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>

    
<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


<!-- 代码块折行 -->

<style type="text/css">
code[class*="language-"], pre[class*="language-"] { white-space: pre !important; }
</style>

    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            // headingsOffset: -205,
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>



    <footer class="page-footer bg-color">
    <div class="container row center-align">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            <span id="year">年份</span>
            <a href="https://zhangyafeii.gitee.io" target="_blank">张亚飞</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                class="white-color">344.5k</span>&nbsp;字
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
            
            <br>
            
            <span id="sitetime">载入运行时间...</span>
            <script>
                function siteTime() {
                    window.setTimeout("siteTime()", 1000);
                    var seconds = 1000;
                    var minutes = seconds * 60;
                    var hours = minutes * 60;
                    var days = hours * 24;
                    var years = days * 365;
                    var today = new Date();
                    var startYear = "2020";
                    var startMonth = "12";
                    var startDate = "18";
                    var startHour = "12";
                    var startMinute = "12";
                    var startSecond = "12";
                    var todayYear = today.getFullYear();
                    var todayMonth = today.getMonth() + 1;
                    var todayDate = today.getDate();
                    var todayHour = today.getHours();
                    var todayMinute = today.getMinutes();
                    var todaySecond = today.getSeconds();
                    var t1 = Date.UTC(startYear, startMonth, startDate, startHour, startMinute, startSecond);
                    var t2 = Date.UTC(todayYear, todayMonth, todayDate, todayHour, todayMinute, todaySecond);
                    var diff = t2 - t1;
                    var diffYears = Math.floor(diff / years);
                    var diffDays = Math.floor((diff / days) - diffYears * 365);
                    var diffHours = Math.floor((diff - (diffYears * 365 + diffDays) * days) / hours);
                    var diffMinutes = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours) /
                        minutes);
                    var diffSeconds = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours -
                        diffMinutes * minutes) / seconds);
                    if (startYear == todayYear) {
                        document.getElementById("year").innerHTML = todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffDays + " 天 " + diffHours +
                            " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    } else {
                        document.getElementById("year").innerHTML = startYear + " - " + todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffYears + " 年 " + diffDays +
                            " 天 " + diffHours + " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    }
                }
                setInterval(siteTime, 1000);
            </script>
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/zhangyafeii" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="https://gitee.com/zhangyafeii" class="tooltipped" target="_blank" data-tooltip="访问我的Gitee" data-position="top" data-delay="50">
        <i class="fab fa-google-plus"></i>
    </a>



    <a href="mailto:zhangyafeii@foxmail.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=1271570224" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 1271570224" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>







    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script src="/js/search.js"></script>
<script type="text/javascript">
$(function () {
    searchFunc("/" + "search.xml", 'searchInput', 'searchResult');
});
</script>
    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>
    <script src="/js/cursor.js"></script>

    <!-- Global site tag (gtag.js) - Google Analytics -->


    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    

    

    
    <script type="text/javascript" src="/libs/background/ribbon-dynamic.js" async="async"></script>
    
    
    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
